import time
from datetime import datetime

from fastapi import APIRouter
from fastapi.params import Form
from pydantic import BaseModel
from starlette.requests import Request

from business.base.AjaxJson import AjaxJson
from business.base.constant import Constant
from utils.MySqlUtil import MySqlUtil
from utils.RedisUtil import RedisUtil
from utils.TokenUtil import TokenUtil
from utils.snowflakeId.xuehuaid import IdWorker

router = APIRouter(
    prefix="/mgrUser",
    tags=["mgrUser"],
    responses={404: {"description": "Not found"}},
)


class MgrUser(BaseModel):
    userName: str = None
    password: str = None
    nickname: str = None


@router.post("/mgrLogin")
async def mgrLogin(user: MgrUser):
    result = AjaxJson()
    result.code = 'failure'
    result.msg = '用户名或密码错误'
    db = MySqlUtil()
    sql = "SELECT * FROM mgr_user t WHERE t.user_name = %s and  t.user_pwd = %s"
    data = db.query(sql, (user.userName, user.password))
    if len(data) > 0:
        result.code = 'success'
        result.msg = '登陆成功'
        user_id = data[0]['id']
        token = TokenUtil.create_jwt_token(user_id)
        time_val = time.time()
        redis = RedisUtil()
        redis.hset(user_id, 'token', token)
        redis.hset(user_id, 'time', time_val)
        nickname = data[0]['nickname']
        result.data = {'token': token, 'nickname': nickname}
    return result


@router.get("/checkToken")
async def checkToken(request: Request):
    j = AjaxJson()
    try:
        token = request.headers.get('token')
        user_id = TokenUtil.checkToke(token)
        redis = RedisUtil()
        token_info = redis.hgetall(user_id)
        if token == token_info['token']:
            now_time = time.time()
            token_time = float(token_info['time'])
            time_diff = now_time - token_time
            if time_diff < 30 * 60:
                sql = 'select count(1) from mgr_user mu where mu.id = %s '
                count = MySqlUtil().get_count(sql, (user_id,))
                if count > 0:
                    j.code = 'success'
                    j.msg = 'token有效'
                    return j
        j.code = "failure"
        j.msg = "登录失效"
        redis.delete(user_id)
    except Exception as e:
        j.code = "failure"
        j.msg = "登录失效"
        print(e)
    return j


@router.get("/getAdminCount")
async def getAdminCount():
    j = AjaxJson()
    try:
        db = MySqlUtil()
        sql = 'SELECT COUNT(1) FROM mgr_user '
        result = db.get_count(sql, None)
        j.data = result
        j.code = 'success'
        j.msg = '获取管理员数量成功'
    except Exception as e:
        j.code = 'failure'
        j.msg = '获取管理员数量失败'
        print(e)
    return j


@router.post("/register")
async def register(user: MgrUser):
    j = AjaxJson()
    try:
        db = MySqlUtil()
        role_id = Constant.get_admin_role_id()  # 后台管理超级管理员角色为1
        user_id = IdWorker().sequence_generator()
        sql = 'SELECT count(1) FROM mgr_user WHERE user_name = %s'
        count = db.get_count(sql, (user.userName,))
        if count > 0:
            j.code = 'failure'
            j.msg = '当前用户名已被使用！'
        else:
            time_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            user_dict = {
                'id': user_id,
                'user_name': user.userName,
                'user_pwd': user.password,
                'nickname': user.nickname,
                'create_date': time_now,
                'create_user': 'admin'
            }
            insert_user = 'INSERT INTO mgr_user(id,user_name,user_pwd,nickname,create_date,create_user) VALUE (%(' \
                          'id)s,%(user_name)s,%(user_pwd)s,%(nickname)s,%(create_date)s,%(create_user)s) '
            db.execute(insert_user, user_dict)

            insert_user_role = 'INSERT INTO user_role_ref(id,user_id,role_id) VALUE (%s,%s,%s)'
            ref_id = IdWorker().sequence_generator()
            db.execute(insert_user_role, (ref_id, user_id, role_id))
            j.code = 'success'
            j.msg = '注册成功'
    except Exception as e:
        j.code = 'failure'
        j.msg = '注册失败'
        print(e)
    return j


@router.get("/logout")
async def logout(request: Request):
    j = AjaxJson()
    try:
        user_id = TokenUtil.checkToke(request.headers.get('token'))
        redis = RedisUtil()
        redis.delete(user_id)
        j.code = 'success'
        j.msg = '退出登录'
    except Exception as e:
        j.code = 'failure'
        j.msg = '操作异常'
        print(e)
    return j


@router.post("/modifyPwd")
async def modifyPwd(request: Request, old_pwd: str = Form(), new_pwd: str = Form()):
    j = AjaxJson()
    try:
        token = request.headers.get("token")
        user_id = TokenUtil.checkToke(token)
        query_user = 'select * from mgr_user mu where mu.id = %s'
        db = MySqlUtil()
        user_info = db.query(query_user, (user_id,))
        user_pwd = user_info[0]['user_pwd']
        if old_pwd == new_pwd:
            j.code = 'failure'
            j.msg = '新的密码与旧的密码不能一致'
            return j
        if old_pwd != user_pwd:
            j.code = 'failure'
            j.msg = '旧密码不正确'
        else:
            update_sql = 'update mgr_user set user_pwd = %s where id = %s'
            db.execute(update_sql, (new_pwd, user_id))
            j.code = 'success'
            j.msg = '密码修改成功'
    except Exception as e:
        j.code = 'failure'
        j.msg = '修改密码失败'
        print(e)
    return j


@router.post("/getUserInfo")
async def getUserInfo(request: Request):
    j = AjaxJson()
    try:
        token = request.headers.get("token")
        user_id = TokenUtil.checkToke(token)
        sql = 'select * from mgr_user mu where mu.id = %s'
        db = MySqlUtil()
        user_list = db.query(sql, user_id)
        if len(user_list) > 0:
            j.data = user_list[0]
            j.code = 'success'
            j.msg = '获取用户信息成功'
        else:
            j.code = 'failure'
            j.msg = '获取用户信息失败'
    except Exception as e:
        j.code = 'failure'
        j.msg = '获取用户信息失败'
        print(e)
    return j


class UserDetails(BaseModel):
    real_name: str = None
    birthday: str = None
    age: str = None
    qq_number: str = None
    email: str = None
    mobile: str = None
    contact_mobile: str = None
    id_no: str = None
    address: str = None
    sex: str = None
    married: str = None


@router.post("/saveUserDetails")
async def saveUserDetails(user: UserDetails, request: Request):
    j = AjaxJson()
    try:
        token = request.headers.get("token")
        user_id = TokenUtil.checkToke(token)
        db = MySqlUtil()
        query_sql = 'select count(1) from user_details ud where ud.mgr_user_id = %s'
        count = db.get_count(query_sql, user_id)
        insert_params = dict(user)
        insert_params['mgr_user_id'] = user_id
        print(insert_params)
        if count > 0:
            sql = 'UPDATE user_details SET real_name=%(real_name)s, birthday=%(birthday)s, age=%(age)s, ' \
                  'qq_number=%(qq_number)s, email=%(email)s, mobile=%(mobile)s, contact_mobile=%(' \
                  'contact_mobile)s, id_no=%(id_no)s, address=%(address)s, sex=%(sex)s, married=%(married)s ' \
                  'WHERE mgr_user_id=%(mgr_user_id)s '
        else:
            sql = 'INSERT INTO user_details (real_name, birthday, age, qq_number, email, mobile, contact_mobile, ' \
                  'id_no, address, sex, married, mgr_user_id) VALUES(%(real_name)s, %(birthday)s, %(age)s, ' \
                  '%(qq_number)s, %(email)s, %(mobile)s, %(contact_mobile)s, %(id_no)s, %(address)s, %(sex)s, ' \
                  '%(married)s, %(mgr_user_id)s) '
        db.execute(sql, insert_params)
        j.code = 'success'
        j.msg = '更新用户详情成功'
    except Exception as e:
        j.code = 'failure'
        j.msg = '更新用户详情失败'
        print(e)
    return j


@router.get("/getUserDetails")
async def getUserDetails(request: Request):
    j = AjaxJson()
    try:
        token = request.headers.get("token")
        user_id = TokenUtil.checkToke(token)
        sql = 'select * from user_details ud where ud.mgr_user_id = %s'
        db = MySqlUtil()
        users = db.query(sql, user_id)
        if len(users) > 0:
            j.data = users[0]
            j.code = 'success'
            j.msg = '获取用户详情成功'
        else:
            j.code = 'failure'
            j.msg = '获取用户详情失败'
    except Exception as e:
        j.code = 'failure'
        j.msg = '获取用户详情失败'
        print(e)
    return j
